/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const { Readable, Writable, Duplex, pipeline } = require("stream");
const { log }  = require("./utils/log")

class YReadable extends Readable {
  constructor() {
    super();
    this.arr = [1, 2, 3, 4, 5, 6, 8, 9, 10];
    this.index = 0;
  }
  _read(size) {
    if (this.index > this.arr.length - 1) {
      this.push(null);
      return;
    }
    this.push(this.arr[this.index++] + "");
  }
}

class YWritable extends Writable {
  constructor() {
    super();
    this.dest = [];
  }

  _write(chunk, _, callback) {
    this.dest.push(chunk.toString());
    callback();
  }
}

class YDuplex extends Duplex {
  constructor() {
    super();
    this.source = [];
    this.index = 0;
  }

  _write(chunk, encoding, callback) {
    this.source.push(chunk.toString());
    callback();
  }

  _read() {
    if (this.index > this.source.length - 1) {
      this.push(null);
      return;
    }
    this.push(this.source[this.index++] + "");
  }
}


export function run_stream() {
  log("------ stream demo start ------")

  const readable = new YReadable();
  const writable = new YWritable();
  const duplex = new YDuplex();

  /**
   * pipeline demo
   */
  pipeline(readable, duplex, writable, (err) => {
    if (err) {
      log("Pipeline failed.", err);
    } else {
      log("Pipeline succeeded.");
    }
  });

  /**
   * pipe demo
   */
  // readable.pipe(duplex).pipe(writable);

  readable.on("end", () => {
    log("writable.dest----" + writable.dest);
    log("duplex.source----" + duplex.source);
    log("------ stream demo end ------")
  });
}

